//
//  ToisoView.m
//  Toiso
//
//  Created by ff xu on 1/7/12.
//  Copyright 2012 codable. All rights reserved.
//

#import "ToisoView.h"

@implementation ToisoView

- (void) awakeFromNib
{
    [self registerForDraggedTypes: [NSArray arrayWithObjects: NSFilenamesPboardType, nil]];
}

- (NSDragOperation) draggingEntered:(id<NSDraggingInfo>)sender
{
    NSPasteboard *pboard = [sender draggingPasteboard];
    NSDragOperation opType = NSDragOperationNone;
    
    if ([[pboard types] containsObject: NSFilenamesPboardType])
        opType = NSDragOperationCopy;
    
    return opType;
}

- (BOOL) performDragOperation:(id<NSDraggingInfo>)sender
{
    static NSString* cue = NULL;
    static NSString* bin = NULL;
    NSPasteboard *pboard = [sender draggingPasteboard];
    BOOL successful = NO;
    if ([[pboard types] containsObject: NSFilenamesPboardType])
    {
        NSArray *files = [pboard propertyListForType: NSFilenamesPboardType];
        if (1 == [files count]) {
            NSString* filename = [files objectAtIndex: 0];
            if ([filename hasSuffix: @".cue"]) {
                cue = filename;
            } else if ([filename hasSuffix: @".bin"]) {
                bin = filename;
            }
        }
        
        if ((NULL == cue) ^ (NULL == bin)) {
            if (cue) {
                bin = [cue stringByReplacingOccurrencesOfString: @".cue" withString: @".bin"];
                if (![[NSFileManager defaultManager] fileExistsAtPath: bin]) {
                    bin = NULL;
                }
            } else {
                cue = [bin stringByReplacingOccurrencesOfString: @".bin" withString: @".cue"];
                if (![[NSFileManager defaultManager] fileExistsAtPath: cue]) {
                    cue = NULL;
                }
            }
        }

        if (cue && bin) {
            NSLog(@"Called");
            successful = [controller convertWithCue: cue withBin: bin];
        }

        cue = bin = NULL;
    }
    
    return successful;
}
- (void)windowWillClose:(NSNotification *)aNotification {
    [NSApp terminate:self];
}
@end
